<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
            margin: 150px;
        }

        #canvas {
            box-shadow: 1px 1px 1px #000;
        }
    </style>
</head>
<body>
<canvas id="canvas">当前浏览器不支持该版本</canvas>


<script src="js/underScore.js"></script>
<script>
    //获取当前画布
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext('2d');
    canvas.width = 1000;
    canvas.height = 600;
    canvas.style.backgroundColor = '#000';


    //    2、小球类
    class Ball {
        constructor(xzb, yzb, color) {
            this.x = xzb;
            this.y = yzb;
            this.color = color;
            this.r = 40;
        }

        /**
         * 绘制小球
         */
        render() {
            ctx.save();
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
            ctx.fillStyle = this.color;
            ctx.fill();
            ctx.restore();
        }
    }


    //    会移动的小球类
    class MoveBall extends Ball {
        constructor(x, y, color) {
            super(x, y, color);             //调用父类

//            量的变化
            this.dx = _.random(-5, 5);
            this.dy = _.random(-5, 5);
            this.dr = _.random(1, 3);
        }

        upData() {
            this.x += this.dx;
            this.y += this.dy;
            this.r -= this.dr;
            if (this.r < 0) {
                this.r = 0;
            }
        }
    }

    //
    //    let ball = new Ball(50, 50, 'red');
    //    ball.render()
    //    实例化小球

    let ballArray = [];
    let colorArr = ['red', 'blue', 'black', 'green', 'pink', 'orange', 'purple', 'yellow'];

    //    监听鼠标移动
    canvas.addEventListener('mousemove', function (e) {
        let ball = new MoveBall(e.offsetX, e.offsetY, colorArr[_.random(0, colorArr.length - 1)]);
        ballArray.push(ball)
    })

    //    开启定时器
    setInterval(function () {
        ctx.clearRect(0, 0, canvas.width, canvas.height)
//        绘制
        for (let i = 0; i < ballArray.length; i++) {
            ballArray[i].render();
            ballArray[i].upData();
        }
    }, 50)
</script>
</body>
</html>